<script lang="ts" setup>
interface DataResource {
  name: string;
  cputotal: number;
  cpuuse: number;
  gpuuse: number;
  gputotal: number;
  diskuse: number;
  disktotal: number;
  memuse: number;
  memtotal: number;
  task: string;
  id: string;
  status: boolean;
  cluster_type: string;
}

interface TaskResource {
  name: string;
  totalstatus: string;
  taskstate: string;
  runtask: number;
  succeedtask: number;
  failedtask: number;
  tasktotal: number;
  cpuuse: number;
  gpuuse: number;
  memuse: number;
  id: string;
  message: string[];
}

interface NodeResource {
  node_address: string;
  cputotal: number;
  cpuuse: number;
  gpuuse: number;
  gputotal: number;
  diskuse: number;
  disktotal: number;
  memuse: number;
  memtotal: number;
}

interface Datatotalcluster {
  code: number;
  data: {
    cpu_total: number;
    cpu_used: number;
    memory_total: number;
    memory_used: number;
    gpu_total: number;
    gpu_used: number;
    storage_used: number;
    storage_total: number;
  };
  clusters: {
    id: string;
    name: string;
    address: string;
    cluster_type: string; // cloud edge
    health_status: boolean;
    last_heartbeat: number;
    cpu_total: number;
    cpu_used: number;
    memory_total: number;
    memory_used: number;
    gpu_total: number;
    gpu_used: number;
    storage_used: number;
    storage_total: number;
  }[];
}

interface Datacluster {
  code: number;
  clusters: {
    id: string;
    name: string;
    address: string;
    cluster_type: string; // cloud edge
    health_status: boolean;
    last_heartbeat: number;
    cpu_total: number;
    cpu_used: number;
    memory_total: number;
    memory_used: number;
    gpu_total: number;
    gpu_used: number;
    storage_used: number;
    storage_total: number;
  };
}

interface Tasktotalcluster {
  code: number;
  data: {
    task_name: string;
    task_phase: string;
    task_replica: number;
    task_active_replicas: number;
    task_succeeded_replicas: number;
    task_failed_replicas: number;
    cpu_total_usage: number;
    memory_total_usage: number;
    conditions: {
      time: number;
      message: string;
    }[];
    pod_resource_metrics: {
      pod_task_dective: {
        pod_task_name: string;
        cpu_total_usage: number;
        memory_total_usage: number;
        ip: string;
      }[];
    };
  }[];
}

interface Submittask {
  apiVersion: string;
  kind: string;
  metadata: {
    name: string;
    namespace: string;
    labels: {
      app: string;
    };
    annotations: {
      description: string[];
    };
  };
  spec: {
    containers: {
      name: string;
      image: string;
      command: string[];
      resources: {
        cpu: string;
        memory: string;
        gpu: number;
      };
      volumeMounts: {
        name: string;
        mountPath: string;
      }[];

      fsFiles: {
        name: string;
        path: string;
      }[];
    }[];
    replica: number;
  };
}

interface datafetchClusterMetrics {
  code: number;
  data: {
    cpu_total: number;
    cpu_used: number;
    memory_total: number;
    memory_used: number;
    gpu_total: number;
    gpu_used: number;
    storage_total: number;
    storage_used: number;
    clusters: {
      id: string;
      name: string;
      address: string;
      cluster_type: string; // 假设只有 'cloud' 或 'edge'
      health_status: boolean;
      last_heartbeat: number; // Unix 时间戳
      cpu_total: number;
      cpu_used: number;
      memory_total: number;
      memory_used: number;
      gpu_total: number;
      gpu_used: number;
      storage_total: number;
      storage_used: number;
      task_num: number;
    }[];
  };
}

// 定义响应式数据
const cpuUsage = reactive({ value: 8, maxValue: 12 });
const memoryUsage = reactive({ value: 4858, maxValue: 8176 });
const gpuUsage = reactive({ value: 1, maxValue: 4 });
const diskUsage = reactive({ value: 3494, maxValue: 10405 });
const flag = ref(0); // 初始化 flag
const CommitTaskstring = ref('');
const cnt = ref(0);
const address = '119.45.169.213:31090';
const Data = ref();
const route = useRoute();
const taskid = ref('');
const taskname = ref('');
const taskdialogisActive = ref(false);
const messages = ref<string[]>([
  '消息一',
  '消息二',
  '消息三'
  // 更多消息
]);
const teststr = ref('');
const testdata = ref();

// 读取 URL 中的 id 参数
const ClusterId = computed(() => {
  return route.params.slug && route.params.slug.length > 0
    ? (route.params.slug[0] as string)
    : '';
});

const dataresources = ref<DataResource[]>([
  {
    name: 'StellarLink',
    cputotal: 12,
    cpuuse: 8,
    gpuuse: 1,
    gputotal: 4,
    diskuse: 15992,
    disktotal: 68830,
    memuse: 4858,
    memtotal: 8176,
    task: '2',
    id: '10',
    status: true,
    cluster_type: 'cloud'
  },
  {
    name: 'GalacticHub',
    cputotal: 6,
    cpuuse: 5,
    gpuuse: 0,
    gputotal: 2,
    diskuse: 29035,
    disktotal: 23191,
    memuse: 3494,
    memtotal: 10405,
    task: '5',
    id: '20',
    status: false,
    cluster_type: 'edge'
  }
]);

const taskresources = ref<TaskResource[]>([
  {
    name: 'LogCleanup',
    taskstate: '123f',
    runtask: 5,
    succeedtask: 15,
    failedtask: 20,
    tasktotal: 40,
    cpuuse: 0.78,
    gpuuse: 0.81,
    memuse: 0.47,
    id: '78',
    totalstatus: 'running',
    message: ['']
  },
  {
    name: 'SignalProcess',
    taskstate: 'gas',
    runtask: 10,
    succeedtask: 10,
    failedtask: 20,
    tasktotal: 40,
    cpuuse: 0.78,
    gpuuse: 0.81,
    memuse: 0.47,
    id: '78j',
    totalstatus: 'failed',
    message: ['']
  }
]);

const noderesources = ref<NodeResource[]>([
  {
    node_address: '172.16.5.100',
    cpuuse: 5,
    cputotal: 6,
    gpuuse: 0,
    gputotal: 2,
    memuse: 2500,
    memtotal: 8000,
    diskuse: 7996,
    disktotal: 34415
  },
  {
    node_address: '172.16.5.101',
    cputotal: 6,
    cpuuse: 3,
    gpuuse: 1,
    gputotal: 2,
    diskuse: 8996,
    disktotal: 34415,
    memuse: 4858,
    memtotal: 8176
  }
]);

const clusterresources = ref<DataResource>({
  name: 'StellarLink',
  cputotal: 1,
  cpuuse: 1,
  gpuuse: 6,
  gputotal: 4,
  diskuse: 2,
  disktotal: 4,
  memuse: 4,
  memtotal: 7,
  task: '1',
  id: '10',
  status: true,
  cluster_type: 'cloud'
});

async function fetchClusterMetrics() {
  const { data } = await useFetch<datafetchClusterMetrics>(
    '/api/v1/cluster/metrics'
  );
  Data.value = data.value;

  cpuUsage.maxValue = data.value.data.cpu_total;
  cpuUsage.value = data.value.data.cpu_used;
  gpuUsage.value = data.value.data.gpu_used;
  gpuUsage.maxValue = data.value.data.gpu_total;
  memoryUsage.value = data.value.data.memory_used;
  memoryUsage.maxValue = data.value.data.memory_total;
  diskUsage.value = data.value.data.storage_used;
  diskUsage.maxValue = data.value.data.storage_total;

  dataresources.value = data.value.data.clusters.map((cluster: any) => ({
    name: cluster.name,
    cputotal: cluster.cpu_total,
    cpuuse: cluster.cpu_used,
    gpuuse: cluster.gpu_used,
    gputotal: cluster.gpu_total,
    diskuse: cluster.storage_used,
    disktotal: cluster.storage_total,
    memuse: cluster.memory_used,
    memtotal: cluster.memory_total,
    task: cluster.task_num,
    id: cluster.id,
    status: cluster.health_status,
    cluster_type: cluster.cluster_type
  }));
}

async function fetchSingleClusterMetrics(clusterId: string) {
  const { data } = await useFetch(`/api/v1/cluster/metrics/${clusterId}`);

  testdata.value = data.value.data.address;
  cpuUsage.value = data.value.data.cpu_used;
  cpuUsage.maxValue = data.value.data.cpu_total;
  gpuUsage.value = data.value.data.gpu_used;
  gpuUsage.maxValue = data.value.data.gpu_total;
  memoryUsage.value = data.value.data.memory_used;
  memoryUsage.maxValue = data.value.data.memory_total;
  diskUsage.value = data.value.data.storage_used;
  diskUsage.maxValue = data.value.data.storage_total;

  clusterresources.value.name = data.value.data.name;
  clusterresources.value.cluster_type = data.value.data.cluster_type;
}

async function fetchTaskMetrics(clusterId: string) {
  const { data } = await useFetch(`/api/v1/task/metrics/${clusterId}`);
  taskresources.value = data.value.data.map((task: any) => ({
    name: task.task_name,
    totalstatus: task.task_phase,
    runtask: task.task_active_replicas,
    succeedtask: task.task_succeeded_replicas,
    failedtask: task.task_failed_replicas,
    cpuuse: task.cpu_total_usage,
    gpuuse: task.gpu_total_usage,
    memuse: task.memory_total_usage,
    message: task.conditions.map((condition: any) => condition.message) || [
      '无消息'
    ]
  }));
}

function fetchsubmitTask(data: string) {
  fetch(`/api/v1/task/submit`, {
    method: 'POST', // 请求方法
    headers: {
      'Content-Type': 'text/plain' // 请求体类型，字符串
    },
    body: data // 请求体数据
  })
    .then((response) => response.json()) // 假设返回的是 JSON 格式的数据
    .then((data) => {
      console.log('Task submitted successfully:', data);
    })
    .catch((error) => {
      console.error('Error submitting task:', error);
    });
}

async function fetchNoderesources(clusterId: string) {
  try {
    const { data } = await useFetch(`/api/v1/node/metrics/${clusterId}`);
    cnt.value = cnt.value + 1;
    noderesources.value = data.value.data.map((node: any) => ({
      node_address: node.node_address,
      cputotal: node.cpu_total,
      cpuuse: node.cpu_used,
      gpuuse: node.gpu_used,
      gputotal: node.gpu_total,
      diskuse: node.storage_used,
      disktotal: node.storage_total,
      memuse: node.memory_used,
      memtotal: node.memory_total
    }));
  } catch (error) {
    console.error('请求失败:', error);
  }
}

function handleTaskItemSelected(Taskid: { value: string }) {
  const selectedTask = taskresources.value.find(
    (task) => task.id === Taskid.value
  );
  if (selectedTask) {
    //console.log('选中的任务数据:', selectedTask);
    taskid.value = Taskid.value; // 更新任务ID
    taskname.value = selectedTask.name;
    messages.value = selectedTask.message; // 更新 messages
    taskdialogisActive.value = true; // 打开对话框
  } else {
    console.error('未找到匹配的任务!');
  }
}

taskresources.value.forEach((task) => {
  task.taskstate = `${task.runtask}/${task.succeedtask}/${task.failedtask}`;
});

function submitTask() {
  fetchsubmitTask(CommitTaskstring.value);
}

function toggleFlag() {
  if (flag.value === 1) {
    // 如果 flag 切换为 1，且 selectedInfo 有效，立即调用 fetchSingleClusterMetrics
    fetchSingleClusterMetrics(ClusterId.value as string);
    fetchTaskMetrics(ClusterId.value as string);
  } else if (flag.value === 0) {
    // 如果切换回全局视图，立即调用 fetchClusterMetrics
    fetchClusterMetrics();
  }
}

let intervalId: ReturnType<typeof setInterval>;
watch(ClusterId, (newClusterId) => {
  flag.value = newClusterId ? 1 : 0;
  clusterresources.value.id = ClusterId.value;
});

onBeforeMount(() => {
  if (!route.params.slug || route.params.slug.length === 0) {
    flag.value = 0; // 如果 ClusterId 为空，flag 置 0
    fetchClusterMetrics();
  } else {
    flag.value = 1;
    fetchSingleClusterMetrics(ClusterId.value as string);
    fetchNoderesources(ClusterId.value as string);
    fetchTaskMetrics(ClusterId.value as string);
  }
});

// 组件挂载时设置定时器
onMounted(() => {
  fetchClusterMetrics(); // 初次加载全局数据
  intervalId = setInterval(() => {
    if (flag.value === 0) {
      fetchClusterMetrics(); // 当 flag == 0 时更新全局数据
    } else if (flag.value === 1) {
      fetchSingleClusterMetrics(ClusterId.value as string); // 当 flag == 1 且 selectedInfo 有效时更新单个集群数据
      fetchNoderesources(ClusterId.value as string);
      fetchTaskMetrics(ClusterId.value as string);
    }
  }, 10000); // 每10秒检查一次
});

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<template>
  <v-container>
    <v-card variant="text" color="surface-variant">
      <v-label
        v-if="flag == 0"
        class="text-h5"
        style="font-weight: bold; color: black"
      >
        当前视角：全局
      </v-label>

      <v-label v-else class="text-h5" style="font-weight: bold; color: black">
        当前视角：
        <span v-if="clusterresources.cluster_type === 'cloud'">
          云集群{{ clusterresources.name }}
        </span>
        <span v-else> 边集群{{ clusterresources.name }} </span>
      </v-label>
    </v-card>

    <v-card class="main-card mb-4" variant="text" color="surface-variant">
      <v-row justify="center" align="center">
        <v-col cols="12" md="3" class="d-flex justify-center">
          <v-card
            class="chart-card"
            outlined
            rounded="0"
            variant="text"
            color="surface-variant"
          >
            <SchedulerBar
              central-label="CPU使用率"
              :central-sub-label="`${cpuUsage.value}/${cpuUsage.maxValue}`"
              :used="cpuUsage.value"
              :remaining="cpuUsage.maxValue - cpuUsage.value"
            />
          </v-card>
        </v-col>

        <v-col cols="12" md="3" class="d-flex justify-center">
          <v-card
            class="chart-card"
            outlined
            variant="text"
            color="surface-variant"
          >
            <SchedulerBar
              central-label="GPU使用率"
              :used="gpuUsage.value"
              :remaining="gpuUsage.maxValue - gpuUsage.value"
              :central-sub-label="`${gpuUsage.value}/${gpuUsage.maxValue}`"
            />
          </v-card>
        </v-col>

        <v-col cols="12" md="3" class="d-flex justify-center">
          <v-card
            class="chart-card"
            outlined
            variant="text"
            color="surface-variant"
          >
            <SchedulerBar
              central-label="内存使用率"
              :central-sub-label="`${memoryUsage.value}/${memoryUsage.maxValue}`"
              :used="memoryUsage.value"
              :remaining="memoryUsage.maxValue - memoryUsage.value"
            />
          </v-card>
        </v-col>

        <v-col cols="12" md="3" class="d-flex justify-center">
          <v-card
            class="chart-card"
            outlined
            variant="text"
            color="surface-variant"
          >
            <SchedulerBar
              central-label="硬盘使用率"
              :used="diskUsage.value"
              :remaining="diskUsage.maxValue - diskUsage.value"
              :central-sub-label="`${diskUsage.value}/${diskUsage.maxValue}`"
            />
          </v-card>
        </v-col>
      </v-row>
    </v-card>

    <v-card v-if="flag == 0" class="mb-4" variant="text">
      <v-card variant="text" color="surface-variant">
        <v-row justify="center">
          <v-col class="d-flex justify-start">
            <v-label class="text-h5" style="font-weight: bold; color: black">
              总视图
            </v-label>
          </v-col>
          <v-col class="d-flex justify-end">
            <v-dialog min-width="1600" max-width="1600">
              <template #activator="{ props: activatorProps }">
                <v-btn
                  v-bind="activatorProps"
                  text="增添任务"
                  color="primary"
                />
              </template>
              <template #default="{ isActive }">
                <v-card title="提交任务信息">
                  <v-card-actions class="d-flex flex-column align-start">
                    <v-form>
                      <v-card>
                        <SchedulerForms />
                        <v-btn
                          class="mt-2"
                          type="submit"
                          block
                          @commit="submitTask"
                          >提交任务</v-btn
                        >
                        <v-btn
                          class="mt-2"
                          text="返回"
                          block
                          @click="isActive.value = false"
                        />
                      </v-card>
                    </v-form>
                  </v-card-actions>
                </v-card>
              </template>
            </v-dialog>
          </v-col>
        </v-row>
      </v-card>
      <SchedulerList :flag="0" :dataresources="dataresources" />
    </v-card>

    <v-card v-else class="mb-4" variant="text">
      <v-card variant="text" color="surface-variant">
        <v-row>
          <v-col class="d-flex justify-start">
            <v-label class="text-h5" style="font-weight: bold; color: black">
              当前集群名:{{ clusterresources.name }}
            </v-label>
          </v-col>
          <v-col class="d-flex justify-end">
            <NuxtLink :to="`/scheduler/`">
              <v-btn color="primary" @click="toggleFlag"> 返回总视图 </v-btn>
            </NuxtLink>
          </v-col>
        </v-row>
      </v-card>
      <SchedulerList
        :flag="1"
        :dataresources="taskresources"
        @item-selected="handleTaskItemSelected"
      />
      <SchedulerList :flag="2" :dataresources="noderesources" />

      <v-dialog v-model="taskdialogisActive" max-width="800">
        <template #default>
          <v-card :title="`当前任务名：${taskname}`">
            <template #text>
              <div>
                <div v-for="(message, index) in messages" :key="index">
                  <p>{{ message }}</p>
                </div>
              </div>
            </template>
            <v-card-actions>
              <v-spacer />
              <v-btn
                color="surface-variant"
                text="exit"
                variant="flat"
                @click="taskdialogisActive = false"
              />
            </v-card-actions>
          </v-card>
        </template>
      </v-dialog>
    </v-card>
  </v-container>
</template>
